package com.create.rdjc.server;

import cn.hutool.db.Entity;
import cn.hutool.db.PageResult;
import com.create.rdjc.jdbc.source.SourceJdbc;
import com.create.rdjc.jdbc.target.TargetJdbc;
import com.create.rdjc.model.FieldModel;
import com.create.rdjc.model.TableModel;
import com.create.rdjc.util.TempUtils;
import lombok.Data;
import org.apache.velocity.VelocityContext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class Service {
    private List<TableModel> tableModels;
    private SourceJdbc sourceJdbc;
    private TargetJdbc targetJdbc;

    public Service(SourceJdbc sourceJdbc, TargetJdbc targetJdbc) {
        this.sourceJdbc = sourceJdbc;
        this.targetJdbc = targetJdbc;
        tableModels = sourceJdbc.selectFields();
    }


    /**
     * 1、人大金仓设置默认模式
     * @param database
     * @return
     */

    public Service setDefaultDataBase(String database){
        targetJdbc.defaultDataBase(database);
        return this;
    }



    /**
     * 2、创建表
     */
    public Service createTable() {
        TempUtils.init();
        VelocityContext context = TempUtils.getContext();
        long tableCount = targetJdbc.getTableCount();
        context.put("tableCount", tableCount);
        context.put("data", tableModels);
        String createTable = TempUtils.startVelocity("temp/tableFields.vm", context);
        targetJdbc.createTable(createTable);
        return this;
    }

    /**
     * 4、修改序列启始值
     * id自增时需要修改序列
     */
    public Service updateSequencesStartValue() {
        Map<String, Integer> map = new HashMap<>();
        tableModels.forEach(m -> {
            for (FieldModel field : m.getFields()) {

                if (field.getAutoId().equals("1")) {
                    Integer maxId = targetJdbc.getMaxId(m.getTableEn(), field.getFieldEn());
                    String s = targetJdbc.selectSequencesName(m.getTableEn());
                    map.put(s, maxId + 1);
                }
            }
        });

        targetJdbc.updateSequencesBach(map);
        return this;
    }


    /**
     * 3、复制数据
     */
    public Service insertData() {

        for (TableModel table : tableModels) {

            int pageNumber = 0;

            while (true) {
                PageResult<Entity> all = sourceJdbc.findAll(table.getTableEn(), pageNumber++, 1000);
                if (all.size() > 0) {
                    try {
                        targetJdbc.insert(all);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    pageNumber = 0;
                    if (all.isLast()) {
                        break;
                    }
                }
            }
        }
        return this;
    }
}
